package v1

import (
	"github.com/gin-gonic/gin"
	"manager/auth"
	"manager/bll"
	"manager/errors"
	"manager/model"
	"manager/server/web/middleware"
	"manager/utils"
)

var RouteList = &routeList{}

func init() {
	// 注册路由
	RegisterRouter(RouteList)
}

type routeList struct{}

func (a *routeList) Init(r *gin.RouterGroup) {
	g := r.Group("/route", middleware.Auth())
	{
		g.POST("/create", a.create)
		g.POST("/update", a.update)
		g.POST("/list", a.list)
		g.POST("/delete", a.delete)
		g.POST("/detail", a.find)
	}

	appG := r.Group("app/route", middleware.Auth())
	{
		appG.POST("/create", a.create)
		appG.POST("/update", a.update)
		appG.POST("/list", a.list)
		appG.POST("/delete", a.delete)
		appG.POST("/detail", a.find)
	}
}

func (a *routeList) create(c *gin.Context) {
	var (
		in  = &model.RouteListCreateRequest{}
		err error
	)

	if err = c.ShouldBindJSON(in); err != nil {
		c.Error(err)
		return
	}

	if err = bll.RouteList.Create(c.Request.Context(), in); err != nil {
		c.Error(err)
		return
	}
	utils.ResponseOk(c, nil)
}

func (a *routeList) update(c *gin.Context) {
	var (
		in  = &model.RouteListUpdateRequest{}
		err error
	)

	if err = c.ShouldBindJSON(in); err != nil {
		c.Error(err)
		return
	}

	if err = bll.RouteList.Update(c.Request.Context(), in); err != nil {
		c.Error(err)
		return
	}
	utils.ResponseOk(c, nil)
}

func (a *routeList) list(c *gin.Context) {
	var (
		in  = &model.RouteListListRequest{}
		out = &model.RouteListListResponse{}
		err error
	)

	if err = c.ShouldBindJSON(in); err != nil {
		c.Error(err)
		return
	}

	// 车辆校验
	if auth.ContextOs(c.Request.Context()) != "web" {
		if in.EbikeId == 0 {
			c.Error(errors.New("ebikeId is required"))
			return
		}
	}

	// 获取骑行记录
	if out, err = bll.RouteList.List(c.Request.Context(), c.GetHeader("os"), in); err != nil {
		c.Error(err)
		return
	}
	utils.ResponseOk(c, out)
}

func (a *routeList) find(c *gin.Context) {
	var (
		in  = &model.RouteListInfoRequest{}
		out = &model.RouteListInfo{}
		err error
	)

	if err = c.ShouldBindJSON(in); err != nil {
		c.Error(err)
		return
	}

	if in.Id <= 0 {
		c.Error(errors.New("id cant not be zero"))
		return
	}

	var listData *model.RouteListListResponse
	if listData, err = bll.RouteList.List(c.Request.Context(), c.GetHeader("os"), &model.RouteListListRequest{
		Index: 1,
		Size:  1,
		Id:    in.Id,
	}); err != nil {
		c.Error(err)
		return
	}

	if listData != nil && len(listData.List) > 0 {
		out = listData.List[0]
	}

	utils.ResponseOk(c, out)
}

func (a *routeList) delete(c *gin.Context) {
	var (
		in  = &model.RouteListDeleteRequest{}
		err error
	)

	if err = c.ShouldBindJSON(in); err != nil {
		c.Error(err)
		return
	}

	if err = bll.RouteList.Delete(c.Request.Context(), in); err != nil {
		c.Error(err)
		return
	}
	utils.ResponseOk(c, nil)
}
